//
//  HyqAppointmentController.swift
//  约麻
//
//  Created by Syrena on 2017/7/20.
//  Copyright © 2017年 Sweet. All rights reserved.
//

import UIKit
import EaseUI
import AVOSCloud
import MBProgressHUD
import MJRefresh

class HyqAppointmentController: EaseConversationListViewController {
    
    var dataArrM=[AVUser]()
    var isfrist = true
    
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = false
        getmyfriends()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "会话"
        automaticallyAdjustsScrollViewInsets = true
        
        showRefreshHeader = false
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { 
            self.getmyfriends()
        })
        
        
    }
    
    func getmyfriends(){
        MBProgressHUD.showAdded(to: view, animated: true)
        var error:EMError?
        let array = EMClient.shared().contactManager.getContactsFromServerWithError(&error)
        let userlist = array as? [String]
        if userlist?.count == 0{
            MBProgressHUD.hideAllHUDs(for: view, animated: true)
            self.tableViewDidTriggerHeaderRefresh()
            tableView.mj_header.endEditing(true)
            return
        }
        let que = AVQuery(className: "_User")
        dataArrM.removeAll()
        for username in userlist!{
            que.whereKey("username", equalTo: username)
            que.findObjectsInBackground({ [weak self](objects, error) in
                if error == nil{
                    let userobjects = objects as? [AVUser]
                    self?.dataArrM.append((userobjects?.last)!)
                    if self?.dataArrM.count == userlist?.count{
                        MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                        self?.dataSource = self
                        self?.delegate = self
                        self?.tableView.mj_header.endEditing(true)
                        self?.tableViewDidTriggerHeaderRefresh()
                    }
                }else{
                    MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                    self?.tableView.mj_header.endEditing(true)
                    self?.tableViewDidTriggerHeaderRefresh()
                    return
                }
            })
        }
    }
}

extension HyqAppointmentController:EaseConversationListViewControllerDelegate,EaseConversationListViewControllerDataSource{
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, modelFor conversation: EMConversation!) -> IConversationModel! {
        let model = EaseConversationModel(conversation: conversation)
        if model?.conversation.type == EMConversationTypeChat{
            for user in dataArrM{
                if user.username == conversation.conversationId{
                    if let name = user.object(forKey: "name") as? String{
                        model?.title = name
                    }else{
                        model?.title = user.username
                    }
                    
                    if let image = user.object(forKey: "headimage") as? String{
                        model?.avatarURLPath = image
                    }else{
                        model?.avatarImage = UIImage(named: "茶叶")
                    }
                }
            }
        }
        return model
    }
    /*EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
     if (model.conversation.type == EMConversationTypeChat) {
     //在这里显示会话列表的头像和昵称
     if (1) {
     for (AVUser *user in self.friendarray) {
     if ([user.username isEqualToString:conversation.conversationId]) {
     model.title = [user objectForKey:@"name"];;
     model.avatarImage = [UIImage imageNamed:[user objectForKey:@"icon"] ];
     [self.tableView reloadData];
     }
     }
     }else{
     
     }
     
     }*/
    
    
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, didSelect conversationModel: IConversationModel!) {
        let str = conversationModel.conversation.conversationId
        let que = AVQuery(className: "_User")
        que.whereKey("username", equalTo: str!)
        que.findObjectsInBackground { [weak self](object, error) in
            if error == nil{
                let user = object?.last as? AVUser
                let vc = ZWHChatViewController(conversationChatter: user?.username, conversationType: EMConversationTypeChat)
                vc?.user = user
                
                self?.navigationController?.pushViewController(vc!, animated: true)
            }
        }
        
    }
}
